package com.steven.ourcontest.me.view

import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat.checkSelfPermission
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.daimajia.numberprogressbar.NumberProgressBar
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseFragment
import com.steven.ourcontest.base.DialogBuilder
import com.steven.ourcontest.chat.bean.WSApplyFriendResponse
import com.steven.ourcontest.chat.bean.WSMessageResponse
import com.steven.ourcontest.chat.helper.MessageHelper
import com.steven.ourcontest.information.bean.IdentifyStatusResponse
import com.steven.ourcontest.information.viewmodel.IdentifyViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.me.bean.TeamInfoBanner
import com.steven.ourcontest.me.viewmodel.MeViewModel
import com.steven.ourcontest.me.widget.GlideRoundTransform
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.FileRequestBody
import com.steven.ourcontest.net.NetConstants.ICON_BASE_URL
import com.steven.ourcontest.net.RetrofitCallback
import com.steven.ourcontest.utils.Identity
import com.steven.ourcontest.utils.RxBus
import com.steven.ourcontest.utils.WebSocketOpen
import com.steven.ourcontest.utils.openAlbum
import com.steven.ourcontest.utils.plusAssign
import com.steven.ourcontest.utils.toast
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.size
import kotlinx.android.synthetic.main.fragment_mine.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class MeFragment : BaseFragment() {
    private val identifyViewModel: IdentifyViewModel by activityViewModels()
    private val meViewModel: MeViewModel by viewModels()
    private var capturPath: String = ""
    private val iconClickDialog by lazy {
        context?.let { context ->
            DialogBuilder(context)
                .setCancelable(true)
                .setAnim(R.style.dialogStyle)
                .addListener(R.id.tv_upload_icon, View.OnClickListener {
                    openAlbum(context)
                })
                .build(R.layout.dialog_upload_icon)
        }
    }
    private val teamList = ArrayList<TeamInfoBanner>()

    override fun getViewId(): Int? {
        return R.layout.fragment_mine
    }

    override fun initSmartRefresh(): SmartRefreshLayout? {
        return smart_refresh
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
    }

    private fun initView() {
        identifyViewModel.queryUserDetail()
        meViewModel.queryUrl()
        banner_my_team?.loadImage { _, model, view, _ ->
            if (model is TeamInfoBanner) {
                val tvTeamName: TextView? = view.findViewById(R.id.tv_team_name)
                val tvStatus: TextView? = view.findViewById(R.id.tv_status)
                val tvMatch: TextView? = view.findViewById(R.id.tv_match)
                val tvMember: TextView? = view.findViewById(R.id.tv_member)
                val tvTeamLeader: TextView? = view.findViewById(R.id.tv_team_leader)
                tvTeamName?.text = model.teamName
                when (model.status) {
                    0 -> {
                        tvStatus?.text = "招募状态:关闭"
                    }
                    1 -> {
                        tvStatus?.text = "招募状态:开启"
                    }
                }
                tvMatch?.text = "面向竞赛:${model.matchName}"
                tvMember?.text = "队伍成员:${model.memberNum}人"
                tvTeamLeader?.isVisible = model.belongUserId == LoginController.userId
            }
        }
    }

    private fun initListener() {
        identifyViewModel.identifyStatus.observe(viewLifecycleOwner, Observer {
            updateIdentity(it)
        })
        identifyViewModel.userName.observe(viewLifecycleOwner, Observer {
            if (it?.msg == "success") {
                tv_user_name?.text = it.name
            }
        })
        meViewModel.uploadRes.observe(viewLifecycleOwner, Observer {
            if (it?.msg == "success" && it.data?.iconUrl != null) {
                LoginController.iconUrl = it.data.iconUrl
                Glide.with(this)
                    .load(ICON_BASE_URL + it.data.iconUrl)
                    .placeholder(R.drawable.ic_placeholder)
                    .dontAnimate()
                    .error(R.drawable.ic_avatar)
                    .apply(
                        RequestOptions.bitmapTransform(GlideRoundTransform(context, 10))
                    ).into(iv_icon)
            }
        })
        radius_icon?.setOnClickListener {
            if (!LoginController.isLogin) {
                toast("请先登录")
                return@setOnClickListener
            }
            val window = iconClickDialog?.window
            window?.setGravity(Gravity.BOTTOM)
            window?.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            if (iconClickDialog?.isShowing == false) {
                iconClickDialog?.show()
            }
        }
        ll_setting?.setOnClickListener {
            context?.let { it1 -> AppRouter.startSettingActivity(it1) }
        }
        ll_create_team?.setOnClickListener {
            context?.let { it1 -> AppRouter.startAddTeamActivity(it1) }
        }
        disposables += RxBus.getInstance()
            .toObservable(viewLifecycleOwner, WSApplyFriendResponse::class.java).subscribe {
                updateRedPoint()
            }
        disposables += RxBus.getInstance()
            .toObservable(viewLifecycleOwner, WSMessageResponse::class.java).subscribe {
                updateRedPoint()
            }
        disposables += RxBus.getInstance()
            .toObservable(viewLifecycleOwner, WebSocketOpen::class.java).subscribe {
                tv_message_num?.text = "0"
                tv_message_num?.isVisible = false
            }
        tv_my_friend?.setOnClickListener {
            if (LoginController.isLogin && LoginController.userType != "") {
                context?.let { it1 ->
                    AppRouter.startFriendsActivity(it1)
                }
            } else {
                toast("未通过身份认证")
            }
        }
        meViewModel.userTeamResponse.observe(viewLifecycleOwner, Observer {
            if (smart_refresh?.isRefreshing == true) {
                smart_refresh?.finishRefresh()
            }
            if (it != null) {
                banner_my_team?.isVisible = it.data.isNotEmpty()
                tv_tips?.isVisible = it.data.isEmpty()
                teamList.clear()
                it.data.forEach { info ->
                    teamList.add(TeamInfoBanner(info))
                }
                banner_my_team?.setBannerData(R.layout.item_my_team_list, teamList)
            }
        })
        banner_my_team?.setOnItemClickListener { _, model, _, _ ->
            if (model is TeamInfoBanner) {
                val teamId = model.id
                context?.let { it1 -> AppRouter.openTeamDetailActivity(it1, teamId) }
            }
        }
        tv_my_like?.setOnClickListener {
            context?.let { it1 -> AppRouter.openCollectionActivity(it1) }
        }
        smart_refresh?.setOnRefreshListener {
            meViewModel.queryUserTeam(LoginController.userId)
        }
        meViewModel.queryUserTeam(LoginController.userId)
    }

    private fun updateIdentity(it: IdentifyStatusResponse?) {
        when (it?.status) {
            2 -> {
                ll_identity?.setOnClickListener(null)
                tv_status.text = "已认证"
                tv_identity?.text = when (it.userType) {
                    Identity.TEACHER.value -> {
                        tv_identity?.isVisible = true
                        "老师认证"
                    }
                    Identity.STUDENT.value -> {
                        tv_identity?.isVisible = true
                        "学生认证"
                    }
                    Identity.ADMIN.value -> {
                        tv_identity?.isVisible = true
                        ll_identity?.setOnClickListener {
                            context?.let { it1 -> AppRouter.startAdminManageActivity(it1) }
                        }
                        "管理员认证"
                    }
                    else -> {
                        tv_identity?.isVisible = false
                        ""
                    }
                }
            }
            1 -> {
                ll_identity?.setOnClickListener {
                    context?.let { it1 -> AppRouter.startSelectIdentityActivity(it1) }
                }
                tv_identity?.isVisible = false
                tv_status.text = "认证失败"
            }
            0 -> {
                ll_identity?.setOnClickListener(null)
                tv_status.text = "等待认证中"
                tv_identity?.isVisible = false
            }
            else -> {
                ll_identity?.setOnClickListener {
                    context?.let { it1 -> AppRouter.startSelectIdentityActivity(it1) }
                }
                tv_identity?.isVisible = false
                tv_status?.text = "未认证"
            }
        }
    }

    private fun updateRedPoint() {
        try {
            //更新小红点
            val size = MessageHelper.applyUnReadMap.size + MessageHelper.messageUnReadMap.size
            tv_message_num?.text = size.toString()
            tv_message_num?.isVisible = size != 0
        } catch (e: Exception) {
            tv_message_num?.isVisible = false
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        banner_my_team?.startAutoPlay()
        if (LoginController.isLogin) {
            identifyViewModel.queryUserDetail()
            identifyViewModel.queryIdentifyStatus(LoginController.userId)
            meViewModel.queryUrl()
            tv_uid?.text = "UID:${LoginController.userId}"
        } else {
            tv_identity?.isVisible = false
        }
        updateRedPoint()
        if (LoginController.userType == Identity.ADMIN.value) {
            rl_handle_report?.isVisible = true
            rl_handle_report?.setOnClickListener {
                context?.let {
                    AppRouter.openHandleReportActivity(it)
                }
            }
        } else {
            rl_handle_report?.isVisible = false
        }
        if (LoginController.userType == Identity.ADMIN.value || LoginController.userType == Identity.TEACHER.value) {
            rl_add_match?.isVisible = true
            rl_add_match?.setOnClickListener {
                context?.let { it1 ->
                    AppRouter.openAddMatchActivity(it1)
                }
            }
        }else{
            rl_add_match?.isVisible = false
        }
    }

    override fun onPause() {
        banner_my_team?.stopAutoPlay()
        super.onPause()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> {
                val cursor: Cursor? = data?.data?.let {
                    context?.contentResolver?.query(
                        it,
                        arrayOf(MediaStore.Images.Media.DATA),
                        null,
                        null,
                        null
                    )
                }
                cursor?.moveToFirst()
                capturPath = cursor?.getString(
                    cursor.getColumnIndex(
                        MediaStore.Images.Media.DATA
                    )
                ) ?: ""
                cursor?.close()
                try {
                    if (capturPath == "") {
                        throw Exception("file path is error")
                    }
                    iconClickDialog?.dismiss()
                    val file = File(capturPath)
                    val dialog = DialogBuilder(requireContext())
                        .setCancelable(false)
                        .build(R.layout.dialog_upload)
                    dialog.show()
                    val progressView = dialog.findViewById<NumberProgressBar>(R.id.progress)
                    GlobalScope.launch(Dispatchers.Default) {
                        val resFile = Compressor.compress(requireContext(), file) {
                            size(50 * 1024)
                        }
                        val fileRQ =
                            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), resFile)
                        val realBody =
                            FileRequestBody(fileRQ, object : RetrofitCallback<EmptyResponse>() {
                                override fun onLoading(total: Long, progress: Long) {
                                    super.onLoading(total, progress)
                                    GlobalScope.launch(Dispatchers.Main) {
                                        progressView.progress =
                                            ((progress / total.toFloat()) * 100).toInt()
                                        if (total == progress) {
                                            dialog.dismiss()
                                        }
                                    }
                                }
                            })
                        val body: RequestBody = MultipartBody.Builder()
                            .addFormDataPart("image", resFile.name, realBody)
                            .build()
                        meViewModel.uploadIcon(body)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun login() {
        meViewModel.queryUserTeam(LoginController.userId)
    }

    override fun logout() {
        tv_user_name?.text == "账号信息"
        Glide.with(this).clear(iv_icon)
        ll_identity?.setOnClickListener(null)
        tv_status?.isVisible = false
        tv_status.text = ""
    }
}